package com.studio5704website.infrastructure.service;

import com.studio5704website.core.service.JwtService;
import com.studio5704website.core.user.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Date;
import java.util.Optional;

/**
 * @author 高威
 * token生产工具类
 */
@Deprecated
public class DefaultJwtService implements JwtService {

    private String secret;
    private int sessionTime;

    @Autowired
    public DefaultJwtService(@Value("${jwt.secret}") String secret,
                             @Value("${jwt.sessionTime}") int sessionTime) {
        this.secret = secret;
        this.sessionTime = sessionTime;
    }


    @Override
    public String toToken(User user) {
        return Jwts.builder()
                .setSubject(userAndTime(user))
                .signWith(SignatureAlgorithm.HS512, secret)
                .setIssuedAt(Date.from(Instant.now()))
                .setIssuer("5704website")
                .compact();
//        return Jwts.builder()
//                .setSubject(user.getId())
//                .setExpiration(expireTimeFromNow())
//                .signWith(SignatureAlgorithm.HS512, secret)
//                .compact();
    }

    @Override
    public Optional<String> getSubFromToken(String token) {
        try {
            System.out.println(token);
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            System.out.println(claimsJws.getBody().getSubject());
            String[] res = claimsJws.getBody().getSubject().split(" ");
            if (res.length < 2) {
                return Optional.empty();
            } else {
                return Optional.ofNullable(res[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Optional.empty();
        }
    }

    private String userAndTime(User user) {
        StringBuilder builder = new StringBuilder();
        builder.append(user.getId());
        builder.append(" ");
        builder.append(System.currentTimeMillis());
        System.out.println(builder.toString());
        return builder.toString();
    }
}

